<template>
  <div class="app-container calendar-list-container">
    <!-- filter 条件查询 -->
    <div class="filter-container">
      <el-input clearable @keyup.enter.native="handleFilter" v-model="listQuery.sortName" style="width: 200px;" class="filter-item" placeholder="请输入品类名称" >
      </el-input>
      <el-select v-model="listQuery.sortLv" placeholder="请选择品类级别" clearable class="filter-item" style="width: 250px;">
        <el-option v-for="item in rank" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">{{$t('common.Search')}}</el-button>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-circle-plus-outline" @click="addBtn">{{$t('common.Add')}}</el-button>
      <el-button class="filter-item" type="primary" v-waves  @click="handleDownload" icon="el-icon-download">{{$t('common.Export')}}</el-button>
    </div>
    <!-- table 表格 -->
    <el-table  :data="list" v-loading="loading.list" element-loading-text="给我一点时间" border fit highlight-current-row
      style="width: 100%">      
      <el-table-column align="center" :label="$t('sort')" prop='index'/>
      <el-table-column  align="center" label="图标" prop='sortPic'>
          <template slot-scope="scope">
              <img :src="scope.row.sortPic" style="width:100px;height:100px;" alt="">
          </template>
      </el-table-column>
      <el-table-column  align="center" label="品类名称" prop='sortName'/>
      <el-table-column  align="center" label="品类级别" prop='sortLv'>
          <template slot-scope="scope">
              {{scope.row.sortLv == 1?'特级':scope.row.sortLv == 2?'一级':scope.row.sortLv == 3?'二级':'三级'}}
          </template>
      </el-table-column>
      <el-table-column  align="center" label="创建时间" prop='ctime'>
        <template slot-scope="scope">
          {{scope.row.ctime | parseTime}}
        </template>
      </el-table-column>
      <el-table-column align="center"  label="操作"  class-name="small-padding fixed-width">
        <template slot-scope="scope"> 
           <div class="fx"> 
             <el-button  size="mini" type="danger" @click="del(scope.row.id)">删除</el-button> 
             <el-button  size="mini" type='primary' @click="editBtn(scope.row)">编辑</el-button>
           </div> 
        </template>
      </el-table-column>
    </el-table>
    <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination 
      background 
      @size-change="handleSizeChange" 
      @current-change="handleCurrentChange" 
      :current-page="listQuery.pageNo" 
      :page-sizes="[10, 20, 30, 40]" 
      :page-size="listQuery.pageSize" 
      layout="total, sizes, prev, pager, next, jumper" 
      :total="total">
      </el-pagination>
    </div>
    <!-- dialog 新增编辑品类弹框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialog.add" @close="onclose">
      <el-form :model="addQuery" :rules='addRules' ref="addForm" label-position="right" label-width="120px">        
        <el-form-item label="图标">
            <el-upload
            class="upload-demo"
            :action="''"
            :on-success="handleSuccess"
            :on-remove="handleRemove"  
            :http-request='uploadsortPic'
            ref='sortPic'
            :limit="1"
            :file-list="fileList"
            list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="品类名称" prop='sortName'>
          <el-input  clearable v-model="addQuery.sortName" placeholder="请输入品类名称"></el-input>
        </el-form-item >
        <el-form-item label="品类级别" prop="sortLv">
          <el-select v-model="addQuery.sortLv" placeholder="请选择品类级别" clearable class="filter-item" style="width: 250px;" @change="getSortLv">
            <el-option v-for="item in rank" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.add = false">取消</el-button>
        <el-button type="primary" :loading="loading.add" @click="add" v-if="dialogType == 1">确定</el-button>
        <el-button type="primary" :loading="loading.add" @click="edit" v-else>确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { parseTime } from '@/utils/index'
import { exportExcel} from '@/api/employee'
import { getSort, addSort,updateSort,delSort } from '@/api/agent'
import { fileUpload } from '@/api/system'
export default {
  name: 'agent_join',
  data() {
    return {
      labelPosition: 'right',
      total: 0,
      list: null,
      loading: {
        list: false,
        add: false
      },
      dialog: {
        add: false
      },
      rank:[
        {label:'特级',value:'1'},
        {label:'一级',value:'2'},
        {label:'二级',value:'3'},
        {label:'三级',value:'4'}
      ],
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        sortName:'',
        sortLv: '',    
      },
      addRules:{
        sortName:[
          { required: true, message: '请输入品类名称', trigger: 'blur' },
        ],
        sortLv:[
          { required: true, message: '请选择品类级别', trigger: 'change' },
        ]
      },
      addQuery:{
        sortName:'',
        sortPic:'',
        sortLv:''
      },
      fileList: [],
      dialogType: 1,
      id: '',
      sortLv:''
    }
  },
  created() {
    this.getList()
  },
   computed:{
      dialogTitle () {
      return this.dialogType === 1 ? '新增品类' : '编辑品类'
      },
  },
  methods: {
    //导出
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['序号', '图标', '品类名称','	品类级别','创建时间']
        const filterVal = ['index', 'sortPic', 'sortName','sortLv','ctime']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '品类列表'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
      if (j === 'ctime') {
        return parseTime(v[j])
      }
      else if(j === 'sortLv'){
        return v[j] == 1?'特级':v[j] == 2?'一级':v[j] == 3?'二级':'三级'
      }else {
        return v[j]
      }
      }))
    },
     //关闭表单
    onclose(){
      this.$refs['sortPic'].clearFiles()
      this.fileList = []
    },
    //获取品类列表
    async getList() {
      this.loading.list = true
      const { data } = await getSort(this.listQuery)
      this.list = data.records.map((item, index) => ({index: index + 1, ...item}))
      this.total = data.total
      this.loading.list = false
    },
     //上传品类图标
    async uploadsortPic ({file}) {    
      const fd = new FormData()
      fd.append('file', file)
      fd.append('fileName', 'businessImg')
      const res = await fileUpload(fd)      
     if (res.code === 1) {
        this.fileList = []
        this.fileList.push(res.data)
        this.addQuery.sortPic = this.fileList.join(',')
      }
    },
     //点击新增按钮
    addBtn(){
        if(this.dialogType == 2){
          this.addQuery = {
           sortName:'',
           sortPic:'',
           sortLv:''
          }
        }
      this.dialogType = 1
      this.dialog.add = true
   },
    //点击提交新增
  async add(){
    this.$refs['addForm'].validate(async (valid) => {
      if (valid) {
          this.loading.add = true   
          try {
            const {data}  = await addSort(this.addQuery)                  
            this.$message.success('新增成功')                 
            this.dialog.add = false
            this.getList()                  
          } catch (error) { 
                                
          } 
          this.loading.add = false                                        
      }
      })
    },
   //点击编辑按钮
   editBtn(row){
    this.id = row.id
    this.addQuery.sortPic = row.sortPic 
    this.addQuery.sortName = row.sortName
    this.addQuery.sortLv = row.sortLv == 1? '特级' :row.sortLv == 2 ? '一级' :row.sortLv == 3 ? '二级' : '三级'
    this.sortLv = this.rank.filter(item=>item.label == this.addQuery.sortLv)[0].value
    this.fileList.push({
      name: row.sortName,
      url: row.sortPic 
    })
    this.dialogType = 2
    this.dialog.add = true
   },
   getSortLv(val){
    this.sortLv = val
   },
    //点击提交编辑
  async edit(){
    this.$refs['addForm'].validate(async (valid) => {
      if (valid) {
          this.loading.add = true 
          try {
            const {data}  = await updateSort({...this.addQuery,sortLv:this.sortLv,id:this.id})                  
            this.$message.success('修改成功')                 
            this.dialog.add = false
            this.getList()                  
          } catch (error) { 
                                
          } 
          this.loading.add = false                                        
      }
      })
    },
    //删除品类
    del(id) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
        }).then(async () => {
          try{
            const { data } = await delSort({id})
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            this.getList()
          } catch(error) {

          }
          
        })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val
      this.getList()
    },
    handleRemove(file, fileList) {
      this.addQuery.sortPic = ''
    },
    handleSuccess(response, file, fileList) {
      console.log(fileList);
    },
    handleRemove(file, fileList) {
       this.addQuery.DetailPic = fileList.map(({raw}) => {
            return raw
      })
    },
  },
    
  }

</script>
